<template>
  <div class=" py-1 flex flex-col">
    <!-- 编辑器 -->
    <div class="input-area">
      <div ref="editor" id="editor" @input="edit"  contenteditable="true" data-text="请输入内容..." @paste.native.capture="pasting" class="input-div" >
     
      </div>

      <div class="limit">
          <span>{{textLen}}</span> / <span>1000</span>
      </div>
    </div>
    <!-- 控制组件 -->

    <div class="flex justify-between py-4">
      <div>
        <el-dropdown ref="dropdownDom" trigger="click">
          <span class="el-dropdown-link">
            <div class="icon-btn i-carbon-face-satisfied mr-4"></div>
          </span>
          <template #dropdown>

            <div class="expressions-list">
              <div :key="item._id" v-for="item in props.picList" @click="emitPic(item)" class="expressions">
                <img  class="cursor-pointer" :src="IMG_URL_SERVER +item?.url" :alt="item?.name">
              </div>

            </div>
          </template>
        </el-dropdown>

        <el-upload  v-if="!stopEmitImg"
          ref="uploadRef"
          class="upload-demo inline-block"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="submitUpload"
          :disabled = "disabled"
          @click = "check"
        >
          <div  class="icon-btn i-carbon-image mr-4"></div>
        </el-upload>
        
      </div>
      <button class="btn" @click="commit">评论</button>
    </div>
  </div>

</template>

<script setup lang="ts">
import type { UploadInstance } from 'element-plus'
import { fetchUpload,fetchAddReply,fetchAddToUserReply,fetchAddToUserReplyThird} from '@/server';
import { IMG_URL_SERVER } from "@/config"




const props = withDefaults(defineProps<{
  picList: any[] ,
  handleReload: Function,
  rootCommentId?: string,
  rpId?: string,
  rows?: number,
  stopEmitImg?: boolean,
  stopPasteImg?:boolean,
}>(),{
  picList: ()=>[],
  stopEmitImg:false,
  stopPasteImg:false
})

//route 
const route = useRoute()
//帖子长度
const textLen = ref(0)
//编辑器dom
const editor :any = ref()
//上传图标dom
const uploadRef = ref<UploadInstance>()
//authStore登录用户数据
const authStore = useAuthStore()
//utilsStore
const utilsStore = useUtilsStore()
//下拉菜单Dom
const dropdownDom = ref()

const submitUpload = (file:any) => {
  handleChange(file)
}



//修改时侦听
const edit = ()=>{
  textLen.value = editor.value.innerText.length
}


// 监听粘贴事件
function pasting(event:any) {
  event.preventDefault()//关闭默认行为
  textLen.value = editor.value.innerText.length //更新文字长度
  
  //文字粘贴
  let txt = event.clipboardData.getData('Text')
  console.log(event.clipboardData.getData('Text'))
  if(typeof(txt) == 'string') {
    // 注意代码注入，这代码不会有问题
    editor.value.insertAdjacentText("beforeend",txt)
  }

  
  const items = (event.clipboardData || window.Clipboard).items
  //禁止图片粘贴，保护条款
  if(props.stopPasteImg){
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf('image') !== -1) {
        event.preventDefault()
        return false
      }
    }
  } 

  //图片粘贴
  let file = null
  if(items.length) {
    for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          handleChange(file)
          break
        }
    }
  }
}
// 图片上传
function handleChange(file:any, fileList?:any) {

    let formData = new FormData()
    formData.append('topicImg', file.raw || file)

    fetchUpload(formData).then( img => {
        editor.value.insertAdjacentHTML("beforeend",`<img style="display: inline-block;vertical-align:text-bottom;max-width:90%;" src="${img.url}" alt="${img.name}">`) 

        // if(fileList){
        //   fileList.push(obj)
        //   console.log(fileList) 
        // }    
    })
}
const disabled = ref(false)
const check = ()=>{
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
  }
}

//点击评论
const commit = ()=>{
  //保护条款
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
    return false;
  }
  if(editor.value.innerHTML == ''){
    return ElMessage.error('评论不能为空！')
  }
  if(props.rpId){
    fetchAddToUserReplyThird(props.rpId as string, editor.value.innerHTML)
  } else if(props.rootCommentId){
    fetchAddToUserReply(route.params.id as string, props.rootCommentId as string, editor.value.innerHTML)
  }else{
    fetchAddReply(route.params.id as string, editor.value.innerHTML)
  }
  
  //reload 重载
  props.handleReload && props.handleReload(500)
  editor.value.innerHTML = ''
}

//表情按钮点击发送图片到编辑器
const emitPic = (img:any)=>{
  editor.value.insertAdjacentHTML("beforeend", `<img style="display: inline-block;width: 4rem;height: 4rem;vertical-align:text-bottom;" src="${IMG_URL_SERVER +img.url}" alt="${img.name}">`)
  dropdownDom.value.handleClose()
}

watchEffect(()=>{
  //保护条款
  if(!authStore.isAuthenticated){
    disabled.value = true
  }else{
      disabled.value = false
  }
 
})




</script>

<style lang="scss">
#editor{
  div{
    margin-top: 0.5rem;
  }
}
.input-area{
    position: relative;
    height: auto;
    overflow: over;
    .input-div{
        vertical-align: text-bottom;
        background-color: #fff;
        border:1px solid #ccc;
        outline: none;
        padding: 0.4rem;
        font-size: 0.9rem;
        transition: all 0.4s;
        height: auto;
        min-height: 6.6rem;
        max-height: 15rem;
        overflow-y: auto;
        border-radius: 0.4rem;
        word-wrap: break-word;

        &[contentEditable=true]:empty:not(:focus):before{
          content:attr(data-text);
          color:#aaa;
        }
        
        &:focus{
          border: 1px solid #31baf9;
        }
    }
    .limit{
        position: absolute;
        right: 1rem;
        bottom: 1rem;
      }
}

.expressions-list{
  display: grid;
  padding: 4px;
  grid-template-columns: repeat(4,4rem);
  grid-template-rows: repeat(auto-fill,4rem);
  gap: 4px;
  height: 16rem;

  .expressions{
    display: inline-block;
    width: 4rem;
    height: 4rem;
    position: relative;
    img{
      width: 100%;
      height: 100%;
      object-fit: cover;
      position: absolute;
    }
  }
}

</style>